package cn.fj.hrm.config;

import cn.fj.hrm.basic.constant.MQContant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    /**
     * 自定义配置RabbitTemplate，从而代替了starter-amqp里面自带的RabbitTemplate
     *  添加了JSON工具，它会将接收到的json字符串转化为实体类对象
     * @param connectionFactory
     * @return
     */
    @Bean("rabbitListenerContainerFactory")
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        factory.setPrefetchCount(1);
        return factory;
    }

    @Bean
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange(MQContant.EXCHANGE_HRM_TOPIC)
                .durable(true)
                .build();
    }

    @Bean(MQContant.QUEUE_HRM_SMS)
    public Queue queue_hrm_sms(){
        return QueueBuilder.durable(MQContant.QUEUE_HRM_SMS).build();
    }

    @Bean(MQContant.QUEUE_HRM_EMAIL)
    public Queue queue_hrm_email(){
        return QueueBuilder.durable(MQContant.QUEUE_HRM_EMAIL).build();
    }

    @Bean
    public Binding binding_queue_hrm_sms(@Qualifier(MQContant.QUEUE_HRM_SMS)Queue queue, Exchange exchange){
        return BindingBuilder.bind(queue)
                .to(exchange)
                .with(MQContant.QUEUE_HRM_SMS_ROUTINGKEY)
                .noargs();
    }

    @Bean
    public Binding binding_queue_hrm_email(@Qualifier(MQContant.QUEUE_HRM_EMAIL)Queue queue, Exchange exchange){
        return BindingBuilder.bind(queue)
                .to(exchange)
                .with(MQContant.QUEUE_HRM_EMAIL_ROUTINGKEY)
                .noargs();
    }

}
